<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <link
      rel="stylesheet"
      href="https://unpkg.com/leaflet@1.4.0/dist/leaflet.css"
    />
    <script src="https://unpkg.com/leaflet@1.4.0/dist/leaflet.js"></script>
    <style>
      #mapid {
        height: 600px;
      }
    </style>
  </head>

  <body>
    <div id="mapid"></div>
  </body>
  <script src="./js/coordtransform.js"></script>
  <script>
    // 获取map对象
    let mymap = L.map("mapid").setView([30.508383, 114.393644], 13);

    // 设置底图
    // L.tileLayer("http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png", {
    //   maxZoom: 18,
    // }).addTo(mymap);

    // 多个地图切换
    let baseLayers = {
      Sputnik: L.tileLayer(
        "https://stamen-tiles-{s}.a.ssl.fastly.net/toner-lite/{z}/{x}/{y}{r}.png",
        {
          maxZoom: 18,
        }
      ),
      "CartoDB Positron": L.tileLayer(
        "http://{s}.basemaps.cartocdn.com/light_all/{z}/{x}/{y}.png",
        {
          maxZoom: 18,
        }
      ),
      OSM: L.tileLayer("http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png", {
        maxZoom: 18,
      }).addTo(mymap),
      OpenTopoMap: L.tileLayer(
        "https://{s}.tile.opentopomap.org/{z}/{x}/{y}.png",
        {
          maxZoom: 18,
        }
      ),
    };

    let layerControl = L.control
      .layers(
        baseLayers,
        {},
        {
          position: "topleft",
          collapsed: true,
        }
      )
      .addTo(mymap);

    // 比例尺
    let scale = L.control
      .scale({
        maxWidth: 200,
        metric: true,
        imperial: false,
      })
      .addTo(mymap);

    // 折线
    let latlngs = [
      [30.511452, 114.393746],
      [30.509448, 114.393025],
      [30.507439, 114.392864],
      [30.463468, 114.41508],
      [30.459399, 114.420954],
    ];
    let polyline = L.polyline(latlngs, { color: "red" }).addTo(mymap);

    // 圆形
    let circle = L.circle([30.508383, 114.393644], {
      color: "red",
      fillColor: "#f03",
      fillOpacity: 0.5,
      radius: 100,
    }).addTo(mymap).bindPopup("光谷").openPopup();

    // 标注点
    let marker = L.marker([30.508383, 114.393644]).addTo(mymap);

    // 多边形
    let polygon = L.polygon([
      [30.512004, 114.393077],
      [30.512329, 114.393666],
      [30.511856, 114.393681],
      [30.511848, 114.39308],
    ]).addTo(mymap);

    // 点击弹窗
    marker.bindPopup("LatLng(30.52, 114.31)").openPopup();
    // circle.bindPopup("I am a circle.");
    // polygon.bindPopup("I am a polygon.");

    // 设置点击事件
    function onMapClick(e) {
      mymap.removeLayer(marker);
      marker = new L.marker(e.latlng, { draggable: true });
      mymap.addLayer(marker);
      marker.bindPopup(e.latlng.toString()).openPopup();
    }
    mymap.on("click", onMapClick);

    // 设置数据 显示武汉市以及各区的轮廓
    async function load_shapefile() {
      let url = "https://geo.datav.aliyun.com/areas_v3/bound/420100_full.json";
      const response = await fetch(url);
      const shape_obj = await response.json();
      return shape_obj;
    }
    let geojson = null;
    async function main() {
      const json = await load_shapefile();
      const myStyle = {
        weight: 2,
        opacity: 1,
        color: "green",
        dashArray: "3",
        fillOpacity: 0.1,
      };
      geojson = L.geoJson(json, {
        style: myStyle,
        onEachFeature: onEachFeature,
      });
    }
    main();
    // 高亮选中区域
    function highlightFeature(e) {
      let layer = e.target;

      layer.setStyle({
        weight: 5,
        color: "#fffafa",
        dashArray: "",
        fillColor: "#fffafa",
        fillOpacity: 0.1,
      });

      if (!L.Browser.ie && !L.Browser.opera && !L.Browser.edge) {
        layer.bringToFront();
      }
    }
    // 重置选中区域
    function resetHighlight(e) {
      geojson.resetStyle(e.target);
    }
    function zoomToFeature(e) {
      //   mymap.fitBounds(e.target.getBounds());
    }
    function onEachFeature(feature, layer) {
      layer.on({
        mouseover: highlightFeature,
        mouseout: resetHighlight,
        click: zoomToFeature,
      });
    }

    // 显示武汉市地铁线路
    // 获取高德地图 武汉市地铁路线以及站点geojson数据
    async function getWuhanMetroGeoJson() {
      let url = "./json/wuhanMetroGeoJson.json";
      const response = await fetch(url);
      const wuhanMetroGeoJson = await response.json();
      return wuhanMetroGeoJson;
    }
    // 将获取的线路和站点添加到底图上
    async function addWuhanMetro() {
      const wuhanMetroGeoJson = await getWuhanMetroGeoJson();
      let drwWuhan = L.geoJson(wuhanMetroGeoJson, {
        filter: (feature) => feature.geometry.type === "LineString",
        style: (feature) => getLineStyle(feature.properties.lineID),
      })
        .bindPopup(function (layer) {
          console.log(layer.feature.properties.name);
          return layer.feature.properties.name;
        })
        .addTo(mymap);
      let infoWuhan = L.geoJson(wuhanMetroGeoJson, {
        filter: (feature) => feature.geometry.type === "Point",
        pointToLayer: function (feature, latlng) {
          return L.marker(latlng, {
            icon: getPointIcon(feature.properties.isTransfer),
          });
        },
      })
        .bindPopup(function (layer) {
          let properties = layer.feature.properties;
          let str = `${properties.name}
          </br>${properties.isTransfer ? "可换乘" : ""}
          </br>始发时间(往):${properties.time.go.start}
          </br>末班时间(往):${properties.time.go.end}
          </br>始发时间(返):${properties.time.back.start}
          </br>末班时间(返):${properties.time.back.end}`;
          return str;
        })
        .addTo(mymap);
      return [drwWuhan, infoWuhan];
    }
    async function addToMap() {
      let [drwWuhan, infoWuhan] = await addWuhanMetro();
      let overlayMaps = {
        地铁路线: drwWuhan,
        地铁站点: infoWuhan,
      };
      L.control
        .layers({}, overlayMaps, {
          position: "topleft",
          collapsed: true,
        })

        .addTo(mymap);
    }
    addToMap();
    // 根据站点类型显示对应图标
    function getPointIcon(isTransfer) {
      let metroIcon = L.icon({
        iconUrl: "./images/metro.png",
        iconSize: [12, 12],
        iconAnchor: [6, 6],
        popupAnchor: [0, 0],
      });
      let transferIcon = L.icon({
        iconUrl: "./images/transfer.png",
        iconSize: [12, 12],
        iconAnchor: [6, 6],
        popupAnchor: [0, 0],
      });
      switch (isTransfer) {
        case true:
          return transferIcon;
          break;
        case false:
          return metroIcon;
          break;

        default:
          break;
      }
    }

    // 根据地铁线路显示对应颜色
    function getLineStyle(lineID) {
      const colorArr = {
        420100034364: "#bdb76b",
        420100024404: "#dc143c",
        420100024331: "#7fffd4",
        420100034395: "#b0c4de",
        900000068659: "#7b68ee",
        420100024335: "#00008b",
        900000044148: "#adff2f",
        900000044147: "#66cdaa",
        900000125965: "#ffc0cb",
        900000073743: "#d8bfd8",
        900000090803: "#8b008b",
        900000075739: "#ffff00",
      };
      return {
        weight: 8,
        color: colorArr[lineID],
      };
    }
  </script>
</html>
